package com.open.loan.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.open.loan.domain.req.ReqJulixinTokenModel;
import com.open.loan.utils.HttpUtil;
import com.open.loan.utils.ResponseUtil;
import com.open.system.domain.LoanApplyDO;
import com.open.system.domain.LoanBankDO;
import com.open.system.domain.LoanJuxinliMMobileDO;
import com.open.system.domain.LoanJuxinliMTokenDO;
import com.open.system.domain.LoanJuxinliReportDO;
import com.open.system.domain.LoanJuxinliTokenDO;
import com.open.system.domain.LoanUserDO;
import com.open.system.service.LoanAdminLogService;
import com.open.system.service.LoanApplyService;
import com.open.system.service.LoanBankService;
import com.open.system.service.LoanJuxinliMMobileService;
import com.open.system.service.LoanJuxinliMTokenService;
import com.open.system.service.LoanJuxinliReportService;
import com.open.system.service.LoanJuxinliTokenService;
import com.open.system.service.LoanUserService;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/moblie")
public class VueJuXinliMobileController {
	
	@Autowired
	private LoanBankService loanbankService;
	
	@Autowired
	private LoanJuxinliMTokenService loanJuxinliMTokenService;
	
	@Autowired
	private LoanUserService loanUserService;
	
	@Autowired
	private LoanJuxinliTokenService loanJuxinliTokenService;
	
	@Autowired
	private LoanBankService loanBankService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanJuxinliReportService loanJuxinliReportService;
	
	@Autowired
	private LoanJuxinliMMobileService mMobileService;
	
	public static String client_secret="a0d730a9ebb4411f881b52f5e6d5361a";
	public static String access_token="6aa02e8304cc4ed0abe34b111bf5354f";

	//获取回执信息
	@ApiOperation(value="获取回执信息", notes="")
	@RequestMapping(value ="/getFromReturnInfo",method = RequestMethod.GET)
	public ResponseEntity<String> getFromReturnInfo(HttpServletRequest request,HttpServletResponse response){
				try {
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					loanUserDo=loanUserService.get(loanUserDo.getId());
					Map<String, Object> params=new HashMap<String, Object>();
					params.put("userId", loanUserDo.getId());
					List<LoanBankDO>bankList=loanbankService.list(params);
					if(bankList!=null && bankList.size()>0){
						LoanBankDO bank=bankList.get(0);
						//获取蜜罐--开始--
						//蜜罐和蜜蜂的收费是 查蜜罐送蜜蜂，因此先查蜜缺勤再查蜜蜂。
						//honeyJarRepoert(bank);
						//获取蜜罐--结束--
						String url="https://www.juxinli.com/orgApi/rest/v3/applications/juying";
						List<ReqJulixinTokenModel>selectmodels=new ArrayList<ReqJulixinTokenModel>();
						ReqJulixinTokenModel model=new ReqJulixinTokenModel();
						model.setWebsite("jingdong");
						model.setCategory("e_business");
						selectmodels.add(model);
						Map<String, String> basicMap=new HashMap<String, String>();
						System.out.println("name="+bank.getRealName());
						System.out.println("card="+bank.getIdNo());
						System.out.println("mobile="+bank.getMoblie());
						System.out.println("当前系统编码="+System.getProperty("file.encoding"));
						String userName=bank.getRealName();
						basicMap.put("name",getUTF8StringFromGBKString(userName));
						basicMap.put("id_card_num",bank.getIdNo());
						basicMap.put("cell_phone_num",bank.getMoblie());
						basicMap.put("home_addr","");
						basicMap.put("work_tel","");
						basicMap.put("work_addr","");
						basicMap.put("home_tel","");
						basicMap.put("cell_phone_num2","");
						
						JSONObject jsonNode = new JSONObject(new LinkedHashMap());
						jsonNode.put("selected_website",selectmodels);
						jsonNode.put("basic_info",basicMap);
						jsonNode.put("skip_mobile","false");
						System.out.println("jsonNode="+jsonNode);
						Object returnJson=HttpUtil.sendPostJsonData(url,jsonNode.toString());
						System.out.println("returnJson"+returnJson);
						//获取表单信息完成
						JSONObject jsonObject =JSONObject.parseObject(returnJson.toString());
						String code=jsonObject.getString("code");
						if("65557".equals(code)){
							String data=jsonObject.getString("data");
							JSONObject jsonData =JSONObject.parseObject(data.toString());
							String token=jsonData.getString("token");
							String cell_phone_num=jsonData.getString("cell_phone_num");
							String datasource=jsonData.getString("datasource");
							JSONObject jsonDatasource =JSONObject.parseObject(datasource.toString());
							String website=jsonDatasource.getString("website");
							List<LoanJuxinliMTokenDO>mTokenDOs=loanJuxinliMTokenService.list(params);
							//--操作日志--开始--
							String adminName=bank.getRealName();
							String Module="1";
							String detail=token;
							//loanAdminLogService.saveLog(String.valueOf(bank.getUserId()), adminName, Module, detail);
							//--操作日志--结束--
							if(mTokenDOs!=null && mTokenDOs.size()>0){
								LoanJuxinliMTokenDO mtoken=mTokenDOs.get(0);
								mtoken.setRealName(loanUserDo.getRealName());
								mtoken.setJson(data);
								mtoken.setMobile(cell_phone_num);
								if(!"2".equals(mtoken.getRemark2())){
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
									Date  createTime=mtoken.getCreateTime();
									Date now = new Date();
									Date afterDate = new Date(createTime .getTime() + 599000);
									if(now.getTime()>afterDate.getTime()){
										mtoken.setToken(token);
										mtoken.setCreateTime(new Date());
									 }
								}
								mtoken.setWebsite(website);
								loanJuxinliMTokenService.update(mtoken);
							}else {
								LoanJuxinliMTokenDO mTokenDO=new LoanJuxinliMTokenDO();
								mTokenDO.setCreateTime(new Date());
								mTokenDO.setJson(data);
								mTokenDO.setMobile(cell_phone_num);
								mTokenDO.setToken(token);
								mTokenDO.setRealName(loanUserDo.getRealName());
								mTokenDO.setUserId(loanUserDo.getId());
								mTokenDO.setWebsite(website);
								mTokenDO.setRemark1("1");//1未采集  2已采集
								loanJuxinliMTokenService.save(mTokenDO);
							}
						}else if ("65556".equals(code)) {
							ResponseUtil.toWrite("65556","生成token失败",null, response);
							return null;
						}else if ("65555".equals(code)) {
							ResponseUtil.toWrite("65555","手机号码所在运营商正在维护",null, response);
							return null;
						}else if ("65554".equals(code)) {
							ResponseUtil.toWrite("65554","手机号码不支持认证",null, response);
							return null;
						}else if ("65553".equals(code)) {
							ResponseUtil.toWrite("65553","数据源名称不合法",null, response);
							return null;
						}else if ("65552".equals(code)) {
							ResponseUtil.toWrite("65552","联系人类型不合法",null, response);
							return null;
						}else if ("65545".equals(code)) {
							ResponseUtil.toWrite("65545","联系人手机号码不合法",null, response);
							return null;
						}else if ("65544".equals(code)) {
							ResponseUtil.toWrite("65544","联系人姓名不合法",null, response);
							return null;
						}else if ("65543".equals(code)) {
							ResponseUtil.toWrite("65543","姓名为空或姓名不合法",null, response);
							return null;
						}else if ("65542".equals(code)) {
							ResponseUtil.toWrite("65542","手机号码为空或手机号码不合法",null, response);
							return null;
						}else if ("65541".equals(code)) {
							ResponseUtil.toWrite("65541","身份证号码为空或身份证号码不合法",null, response);
							return null;
						}else if ("65540".equals(code)) {
							ResponseUtil.toWrite("65540","基本信息不能为空",null, response);
							return null;
						}else if ("65539".equals(code)) {
							ResponseUtil.toWrite("65539","机构账号已过期",null, response);
							return null;
						}else if ("65538".equals(code)) {
							ResponseUtil.toWrite("65538","机构账号已冻结",null, response);
							return null;
						}else if ("65537".equals(code)) {
							ResponseUtil.toWrite("65537","机构账号不存在",null, response);
							return null;
						}
						
					}else {
						ResponseUtil.toWrite("203","请先认证银行卡",null, response);
						return null;
					}
				
				} catch (Exception e) {
					e.printStackTrace();
					ResponseUtil.toWrite("202","获取回执信息失败",null, response);
					return null;
				}
				ResponseUtil.toWrite("200","获取回执信息成功",null, response);
				return null;
		}
	
	
	//采集请求
	@ApiOperation(value="采集请求", notes="")
	@RequestMapping(value ="/startcaijiUserInfo",method = RequestMethod.GET)
	public ResponseEntity<String> startcaijiUserInfo(@RequestParam(value="password",required=false)String password,
													@RequestParam(value="code",required=false)String code,
													@RequestParam(value="returnCode",required=false)String returnCode,
													HttpServletRequest request,HttpServletResponse response){
				try {
					System.out.println("1");
					HttpSession session = request.getSession();
					LoanUserDO loanUserDo=(LoanUserDO) session.getAttribute("loanUserDo");
					if(loanUserDo==null){
						ResponseUtil.toWrite("100","请重新登录",null, response);
						return null;
					}
					Map<String, Object> params=new HashMap<String, Object>();
					params.put("userId", loanUserDo.getId());
					//银行卡认证
					LoanBankDO bankDo=null;
					System.out.println("2");
					List<LoanBankDO>bankLists=loanBankService.list(params);
					for (int i = 0; i <bankLists.size(); i++) {
						bankDo=bankLists.get(0);
					}
					if(bankDo==null){
						ResponseUtil.toWrite("101","请先认证银行卡",null, response);
						return null;
					}
					System.out.println("3");
					//判断数据库是否有值--开始--
					List<LoanJuxinliReportDO>reportDOs=loanJuxinliReportService.list(params);
					if(reportDOs!=null && reportDOs.size()>0){
						ResponseUtil.toWrite("102","您已认证过了",null, response);
						return null;
					}
					//判断数据库是否有值--结束--
					System.out.println("4");
					//银行卡认证
					List<LoanJuxinliMTokenDO>mTokenDOs=loanJuxinliMTokenService.list(params);
					if(mTokenDOs!=null && mTokenDOs.size()>0){
						LoanJuxinliMTokenDO mTokenDO=mTokenDOs.get(0);
						if("2".equals(mTokenDO.getRemark1())){
							ResponseUtil.toWrite("10005","您已经认证过了",null, response);
							return null;
						}
						String url="https://www.juxinli.com/orgApi/rest/v2/messages/collect/req";
						Map<String, String> caijiMap=new HashMap<String, String>();
						caijiMap.put("token",mTokenDO.getToken());//获取回执信息的值
						caijiMap.put("account",mTokenDO.getMobile());
						caijiMap.put("password",password);
						if("10001".equals(returnCode)||"10002".equals(returnCode)){
							caijiMap.put("captcha",code);
							caijiMap.put("type","SUBMIT_CAPTCHA");
						}else {
							caijiMap.put("captcha","");
							caijiMap.put("type","");
						}
						caijiMap.put("website",mTokenDO.getWebsite());//获取回执信息的值
						System.out.println("开始走接口信息");
						Object returnJson=HttpUtil.sendPostJsonData(url,JSON.toJSONString(caijiMap));
						System.out.println("接口信息已回调");
						System.out.println(returnJson.toString());
						JSONObject jsonObject =JSONObject.parseObject(returnJson.toString());
						System.out.println("jsonObject="+jsonObject);
						if("true".equals(jsonObject.getString("success"))){
							String data=jsonObject.getString("data");
							System.out.println("data="+data);
							JSONObject jsonData=JSONObject.parseObject(data);
							String process_code=jsonData.getString("process_code");
							if ("10002".equals(process_code)||"10001".equals(process_code)) {
								ResponseUtil.toWrite("10002","输入短信验证码",null, response);
								return null;
							}else if ("10003".equals(process_code)) {
								ResponseUtil.toWrite("10003","密码错误",null, response);
								return null;
							}else if ("10004".equals(process_code)) {
								ResponseUtil.toWrite("10004","短信验证码错误",null, response);
								return null;
							}else if ("10006".equals(process_code)) {
								ResponseUtil.toWrite("10006","短信验证码失效系统已自动重新下发",null, response);
								return null;
							}else if ("10007".equals(process_code)) {
								ResponseUtil.toWrite("10007","简单密码或初始密码无法登录",null, response);
								return null;
							}else if ("10008".equals(process_code)) {
								mTokenDO.setRemark1("2");
								//mTokenDO.setRemark2(password);
								loanJuxinliMTokenService.update(mTokenDO);
								honeyJarRepoert(bankDo);
								getMobileInfo(bankDo,mTokenDO.getToken());
								ResponseUtil.toWrite("10008","验证成功",null, response);
								return null;
							}else if ("0".equals(process_code)) {
								ResponseUtil.toWrite("0","请求超时",null, response);
								return null;
							}else if ("10023".equals(process_code)) {
								ResponseUtil.toWrite("10023","查询密码错误",null, response);
								return null;
							}else if ("30000".equals(process_code)) {
								ResponseUtil.toWrite("30000","错误信息",null, response);
								return null;
							}else {
								ResponseUtil.toWrite("0","采集失败",null, response);
								return null;
							}
						}else {
							ResponseUtil.toWrite(jsonObject.getString("success"),jsonObject.getString("message"),null, response);
							return null;
						}
					}
					ResponseUtil.toWrite("202","采集异常",null, response);
					return null;
				} catch (Exception e) {
					e.printStackTrace();
					ResponseUtil.toWrite("202","采集请求信息失败",null, response);
					return null;
				}
		}
	
	
	public void honeyJarRepoert(LoanBankDO bankDo){

		Map<String, Object> tokenParam=new HashMap<String, Object>();
		List<LoanJuxinliTokenDO>tokenDOs=loanJuxinliTokenService.list(tokenParam);
		LoanJuxinliTokenDO tokenDO=new LoanJuxinliTokenDO();
		for (int i = 0; i <tokenDOs.size(); i++) {
			tokenDO=tokenDOs.get(0);
		}
		String url="https://mi.juxinli.com/api/search";
		Map<String, String> params=new HashMap<String, String>();
		params.put("client_secret",tokenDO.getClientSecret());
		params.put("access_token",tokenDO.getAccessToken());
		params.put("name",bankDo.getRealName());
		params.put("id_card",bankDo.getIdNo());
		params.put("phone",bankDo.getMoblie());
		params.put("version","v3");
		String returnJson=HttpUtil.sendGet(url, params);
		JSONObject jsonObject =JSONObject.parseObject(returnJson);
		String code=jsonObject.getString("code");
		String message=jsonObject.getString("message");
		
		if("MIGUAN_SEARCH_SUCCESS".equals(code)){
			String data=jsonObject.getString("data");
			JSONObject jsonData =JSONObject.parseObject(data);
			String user_grid_id=jsonData.getString("user_grid_id");//1
			String iou_statistic=jsonData.getString("iou_statistic");//2
			String user_gray=jsonData.getString("user_gray");//3
			JSONObject jsonUser_gray =JSONObject.parseObject(user_gray);
			String contacts_number_statistic=jsonUser_gray.getString("contacts_number_statistic");//4
			String contacts_rfm=jsonUser_gray.getString("contacts_rfm");//5
			String contacts_closest=jsonUser_gray.getString("contacts_closest");//6
			String contacts_gray_score=jsonUser_gray.getString("contacts_gray_score");//7
			String contacts_relation_distribution=jsonUser_gray.getString("contacts_relation_distribution");//8
			String contacts_query=jsonUser_gray.getString("contacts_query");//9
			
			
			String user_searched_statistic=jsonData.getString("user_searched_statistic");//10
			String user_register_orgs=jsonData.getString("user_register_orgs");//11
			String user_blacklist=jsonData.getString("user_blacklist");//12
			String user_basic=jsonData.getString("user_basic");//13
			String auth_org=jsonData.getString("auth_org");//14
			String user_phone_suspicion=jsonData.getString("user_phone_suspicion");//15
			String user_idcard_suspicion=jsonData.getString("user_idcard_suspicion");//16
			String user_searched_history_by_orgs=jsonData.getString("user_searched_history_by_orgs");//17
			String user_batch_searched_history_by_orgs=jsonData.getString("user_batch_searched_history_by_orgs");//18
			String user_searched_history_by_day=jsonData.getString("user_searched_history_by_day");//19
			String consumer_label=jsonData.getString("consumer_label");//20
			
			LoanJuxinliReportDO reportDO=new LoanJuxinliReportDO();
			reportDO.setCode(code);
			reportDO.setMessage(message);
			reportDO.setUserId(bankDo.getUserId());
			reportDO.setCreateTime(new Date());
			reportDO.setPhone(bankDo.getMoblie());
			reportDO.setRealName(bankDo.getRealName());
			reportDO.setJsondata(data);
			reportDO.setUserGridId(user_grid_id);
			reportDO.setIouStatistic(iou_statistic);
			reportDO.setUserGray(user_gray);
			reportDO.setUserGrayContactsNumberStatistic(contacts_number_statistic);
			reportDO.setUserGrayContactsRfm(contacts_rfm);
			reportDO.setUserGrayContactsClosest(contacts_closest);
			reportDO.setUserGrayContactsGrayScore(contacts_gray_score);
			reportDO.setUserGrayContactsRelationDistribution(contacts_relation_distribution);
			reportDO.setUserGrayContactsQuery(contacts_query);
			reportDO.setUserSearchedStatistic(user_searched_statistic);
			reportDO.setUserRegisterOrgs(user_register_orgs);
			reportDO.setUserBlacklist(user_blacklist);
			reportDO.setUserBasic(user_basic);
			reportDO.setAuthOrg(auth_org);
			reportDO.setUserPhoneSuspicion(user_phone_suspicion);
			reportDO.setUserIdcardSuspicion(user_idcard_suspicion);
			reportDO.setUserSearchedHistoryByOrgs(user_searched_history_by_orgs);
			reportDO.setUserBatchSearchedHistoryByOrgs(user_batch_searched_history_by_orgs);
			reportDO.setUserSearchedHistoryByDay(user_searched_history_by_day);
			reportDO.setConsumerLabel(consumer_label);
			loanJuxinliReportService.save(reportDO);
			
			//申请认证修改------开始
			LoanApplyDO applyDO=new LoanApplyDO();
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("userId",bankDo.getUserId());
			List<LoanApplyDO>applyDOs=loanApplyService.list(map);
			for (int i = 0; i <applyDOs.size(); i++) {
				applyDO=applyDOs.get(0);
			}
			applyDO.setCreditAuth("2");;//['0待完善', '1审核中', '2认证成功', '3认证失败']
			loanApplyService.update(applyDO);
			//申请认证修改------结束
			
		}
	}
	
	
	//成功运营商电话
	public void  getMobileInfo(LoanBankDO bankDo,String token){
		String url="https://www.juxinli.com/api/access_raw_data_by_token";
		Map<String, String> params=new HashMap<String, String>();
		params.put("client_secret",client_secret);
		params.put("access_token",access_token);
		params.put("token",token);
		String returnJson=HttpUtil.sendGet(url, params);
		LoanJuxinliMMobileDO mobileDO=new LoanJuxinliMMobileDO();
		mobileDO.setJsonData(returnJson);
		mobileDO.setCreateTime(new Date());
		mobileDO.setUserId(bankDo.getUserId());
		mobileDO.setRealName(bankDo.getRealName());
		mMobileService.save(mobileDO);
	}
	
	
	public static String getUTF8StringFromGBKString(String gbkStr) {  
        try {  
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            throw new InternalError();  
        }  
    }  
      
    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
        int n = gbkStr.length();  
        byte[] utfBytes = new byte[3 * n];  
        int k = 0;  
        for (int i = 0; i < n; i++) {  
            int m = gbkStr.charAt(i);  
            if (m < 128 && m >= 0) {  
                utfBytes[k++] = (byte) m;  
                continue;  
            }  
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
        }  
        if (k < utfBytes.length) {  
            byte[] tmp = new byte[k];  
            System.arraycopy(utfBytes, 0, tmp, 0, k);  
            return tmp;  
        }  
        return utfBytes;  
    }
	
	
			
}
